package main

import (
	"context"
	"kitex-demo/internal/user/dao"
	"kitex-demo/kitex_gen/api/user"

	"github.com/cloudwego/kitex/pkg/klog"
)

// UserServiceImpl 实现 IDL 定义的 UserService 接口
type UserServiceImpl struct{}

// Register 实现注册接口
func (s *UserServiceImpl) Register(ctx context.Context,
	req *user.RegisterRequest) (*user.RegisterResponse, error) {
	klog.Infof("Received Register request: username=%s", req.Username)

	// 1. 参数校验（简化版，实际可加长度/字符校验）
	if req.Username == "" || req.Password == "" {
		return &user.RegisterResponse{
			Code: 400,
			Msg:  "username or password cannot be empty",
		}, nil
	}

	// 2. 调用 DAO 层创建用户
	userID, err := dao.CreateUser(req.Username, req.Password)
	if err != nil {
		// 区分“用户名已存在”和其他数据库错误
		if err.Error() == "username already exists" {
			return &user.RegisterResponse{
				Code: 409,
				Msg:  err.Error(),
			}, nil
		}
		klog.Errorf("CreateUser failed: %v", err)
		return &user.RegisterResponse{
			Code: 500,
			Msg:  "internal server error",
		}, nil
	}

	// 3. 返回成功响应
	return &user.RegisterResponse{
		Code:   0,
		Msg:    "register success",
		UserId: userID,
	}, nil
}
